import React, {useState, useEffect} from 'react'
import {Container, Header, Content, Footer} from './style'

import defaultSettings from '../../defaultSettings'

import {Form, Input, Button, Checkbox, Tooltip, Row, Col, message, notification} from 'antd'
import { UserOutlined, LockOutlined, SafetyOutlined, ArrowLeftOutlined } from '@ant-design/icons'

import LoginRequest from '../../request/login_request'

import store from 'store'

import md5 from 'js-md5'

let timer = null

const login_request = new LoginRequest()

function Login(props){
    const [form] = Form.useForm()
    const {history} = props

    const [isLogin, setIsLogin] = useState(true)

    const [canSendMsg, setCanSendMsg] = useState(true) //是否可以发送验证码
    const [countDownNum, setCountDownNum] = useState(60) //倒计时
    const [codeLoading, setCodeLoading] = useState(false) //发送验证码loading
    const [loginLoading, setLoginLoading] = useState(false) //登录loading

    useEffect(() => {
        form.setFieldsValue({
            username: store.get('username'),
            remember: store.get('remember')
        })
        return () => {
            clearInterval(timer)
        }
    }, [])

    //切换登录、注册
    const toggleLogin = () => {
        if(isLogin){
            setIsLogin(false)
        }else{
            setIsLogin(true)
        }
    }

    // 暂不登录
    const guestLogin = () => {
        history.push('/article/home')
    }

    //发送验证码
    const sendMsgCode = () => {
        let email = form.getFieldValue('username')
        if(email){
            if(!new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$").test(email)){
                return message.warning('邮箱格式不正确！')
            }
        }else{
            return message.warning('请填写邮箱号')
        }
        
        setCodeLoading(true)
        login_request.sendEmail({
            email: email
        }).then(res => {
            message.success('邮箱验证码发送成功！')
            startCountDown()
        }).finally(() => {
            setCodeLoading(false)
        })
    }

    //开始倒计时
    const startCountDown = () => {
        setCanSendMsg(false)
        let time = countDownNum
        timer = setInterval(() => {
            if(time > 0){
                time = time - 1
                setCountDownNum(time)
            }else{
                setCanSendMsg(true)
                clearInterval(timer)
            }
        }, 1000)
    }

    const onFinish = (values) => {
        const {username, password, code, remember} = values
        store.set('remember', remember)
        if(remember){
            store.set('username', username)
        }else{
            store.remove('username')
        }

        setLoginLoading(true)
        if(isLogin){
            login_request.login({
                email: username,
                password: md5(password)
            }).then(res => {
                if(!window.isMobile){
                    notification.success({
                        message: res.message,
                        description: '欢迎进入【八翼小站】，在这里您可以管理您常用的链接、安排您每日的任务计划以及查看查看一些高质量内容，祝您生活愉快！',
                        duration: 5
                    })
                }
                history.push('/article/home')
            }).finally(() => {
                setLoginLoading(false)
            })
        }else{
            login_request.register({
                email: username,
                code,
                password: md5(password)
            }).then(res => {
                if(!window.isMobile){
                    notification.success({
                        message: res.message,
                        description: '欢迎进入【八翼小站】，在这里您可以管理您常用的链接、安排您每日的任务计划以及查看查看一些高质量内容，祝您生活愉快！',
                        duration: 5
                    })
                }
                history.push('/article/home')
            }).finally(() => {
                setLoginLoading(false)
            })
        }
    }

    return (
        <Container>
            <div className="back-home" onClick={() => history.go(-1)}>
                <ArrowLeftOutlined /> 返回
            </div>
            <Header>
                <div className="logo">
                    <img src={defaultSettings.webUrl} alt=""/>
                    <span>{defaultSettings.title}</span>
                </div>
                <div className="web-dec">用心学技术 · 用脚写代码</div>
            </Header>
            <Content>
                <Form
                    name="normal_login"
                    className="login-form"
                    form={form}
                    initialValues={{ remember: false }}
                    onFinish={onFinish}
                >
                    <Form.Item
                        name="username"
                        rules={[{ required: true, message: '请输入你的邮箱!' }]}
                    >
                        <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="邮箱" />
                    </Form.Item>
                    {
                        isLogin ? '' :
                        <Row gutter={8}>
                            <Col span={12}>
                                <Form.Item
                                    name="code"
                                    rules={[{ required: true, message: '请输入邮箱验证码!' }]}
                                >
                                    <Input prefix={<SafetyOutlined className="site-form-item-icon" />} placeholder="邮箱验证码" />
                                </Form.Item>
                            </Col>
                            <Col span={1}>
                                <Button type="primary" loading={codeLoading} disabled={!canSendMsg} ghost onClick={sendMsgCode}>发送验证码 {canSendMsg ? '' : (countDownNum + 's')}</Button>
                            </Col>
                        </Row>
                    }
                    <Form.Item
                        name="password"
                        rules={[
                            {
                                required: true,
                                validator: (rule, value) => {
                                    if(!value){
                                        return Promise.reject('请输入密码！')
                                    }
                                    if (value.trim().length < 6) {
                                        return Promise.reject('密码太短')
                                    }
                                    return Promise.resolve()
                                }
                            }
                        ]}
                    >
                        <Input
                            prefix={<LockOutlined className="site-form-item-icon" />}
                            type="password"
                            placeholder="密码"
                        />
                    </Form.Item>
                    <Form.Item>
                        <Form.Item name="remember" valuePropName="checked" noStyle>
                            <Checkbox>记住我</Checkbox>
                        </Form.Item>

                        <Tooltip className="login-form-forgot" title="请联系管理员">
                            <span style={{color: '#1890ff', cursor: 'pointer'}}>忘记密码</span>
                        </Tooltip>
                    </Form.Item>

                    <Form.Item>
                        <Button type="primary" loading={loginLoading} htmlType="submit" className="login-form-button">
                            {isLogin ? '登录' : '注册'}
                        </Button>
                    </Form.Item>
                    <Row className="login-guest">
                        <span onClick={guestLogin}>暂不登录</span>
                    </Row>
                    <Row className="login-register">
                        <span onClick={toggleLogin}>{isLogin ? '没有账号？点我注册' : '已有账号？点我登录'}</span>
                    </Row>
                </Form>
            </Content>
            <Footer>{defaultSettings.title} ©2020 Created by {defaultSettings.author}</Footer>
        </Container>
    )
}

export default Login